// Request GTFS data and displays it on a Map
// Requested from fusion map
var routes = { "0" : [], "3" : [] };

var stopsGTFS = "SELECT stop_id, stop_name, stop_desc, stop_lat, stop_lon FROM 2459378";
var routesGTFS = "SELECT route_id, route_short_name, route_long_name FROM 2458360 WHERE route_type=";
var tripsGTFS = "SELECT shape_id, trip_headsign FROM 2458508 WHERE route_id='";
var shapeGTFS = "SELECT shape_pt_lat, shape_pt_lon FROM 2458462 WHERE shape_id='";

function loadOrDisplayRoute(typeRoute) {
	var displayed = isDisplayed(typeRoute);
	setDisplayed(!displayed, typeRoute);
	var nbRoutesLoaded = routes[typeRoute].length;
	if (nbRoutesLoaded == 0) {
		loadRoute(typeRoute);
	} else {
		for ( var i = 0; i < nbRoutesLoaded; i++) {
			drawPathRoute(!displayed, typeRoute, routes[typeRoute][i]);
		}
	}
}

// typeRoute : 0=Tram, 3=Bus
function loadRoute(typeRoute) {
	var sql = encodeURIComponent(routesGTFS + typeRoute);
	var query = new google.visualization.Query(
			'http://www.google.com/fusiontables/gvizdata?tq=' + sql);
	query.send(function(response) {
		var rows = response.getDataTable();
		for ( var i = 0; i < rows.getNumberOfRows(); i++) {
			var model = { 'route_id' : rows.getValue(i, 0),
				'route_short_name' : rows.getValue(i, 1),
				'route_long_name' : rows.getValue(i, 2) };
			getTripFromRoute(typeRoute, model);
		}
	});
}

function getTripFromRoute(typeRoute, modelRoute) {
	// TODO Select by service_id got from calendar.txt
	var sql = encodeURIComponent(tripsGTFS + modelRoute['route_id'] + "'");
	var query = new google.visualization.Query(
			'http://www.google.com/fusiontables/gvizdata?tq=' + sql);
	query.send(function(response) {
		var rows = response.getDataTable();
		var shapeids = new Array(); // for better performances
		for ( var i = 0; i < rows.getNumberOfRows(); i++) {
			if ($.inArray(rows.getValue(i, 0), shapeids) == '-1') {
				var model = { 'shape_id' : rows.getValue(i, 0),
					'trip_headsign' : rows.getValue(i, 1) };
				getShapeFromTrip(typeRoute, modelRoute, model);
				shapeids.push(model['shape_id']);
			}
		}
	});
}

function getShapeFromTrip(typeRoute, modelRoute, modelTrip) {
	var sql = encodeURIComponent(shapeGTFS + modelTrip['shape_id'] + "'");
	var query = new google.visualization.Query(
			'http://www.google.com/fusiontables/gvizdata?tq=' + sql);
	query.send(function(response) {
		var rows = response.getDataTable();
		var shapeTripModel = new Array();
		for ( var i = 0; i < rows.getNumberOfRows(); i++) {
			shapeTripModel.push(new google.maps.LatLng(rows.getValue(i, 0),
					rows.getValue(i, 1)));
		}
		var route = new Object();
		route['model'] = modelRoute;
		if (typeRoute == 3) {
			settings['bus']['isDisplayable'] = true;
		} else if (typeRoute == 0) {
			settings['tramway']['isDisplayable'] = true;
		}
		routes[typeRoute].push(route);
		buildPathRoute(typeRoute, route, shapeTripModel);
	});
}

// ligne 1 : #007d48
// ligne 2 : #e72b37
// ligne 3 : #0078be
// ligne 4 : #fdc513
function buildPathRoute(typeRoute, route, shapeTripModel) {
	var modelRoute = route['model'];
	var color = "#FFFFFF";
	var ligne = modelRoute['route_short_name'];
	if (ligne == 1) {
		color = "#007d48";
	} else if (ligne == 2) {
		color = "#e72b37";
	} else if (ligne == 3) {
		color = "#0078be";
	} else if (ligne == 4) {
		color = "#fdc513";
	}
	var tripPath = new google.maps.Polyline({ path : shapeTripModel,
		strokeColor : color, strokeOpacity : 1.0, strokeWeight : 2 });
	route['path'] = tripPath;
	drawPathRoute(true, typeRoute, route);
}

function drawPathRoute(display, typeRoute, route) {
	var tripPath = route['path'];
	if (display) {
		tripPath.setMap(map);
	} else {
		tripPath.setMap(null);
	}
}

function isDisplayed(typeRoute) {
	if (typeRoute == 3) {
		return settings['bus']['isDisplayable'];
	} else if (typeRoute == 0) {
		return settings['tramway']['isDisplayable'];
	}
	return false;
}

function setDisplayed(display, typeRoute) {
	if (typeRoute == 3) {
		settings['bus']['isDisplayable'] = display;
	} else if (typeRoute == 0) {
		settings['tramway']['isDisplayable'] = display;
	}
}

// ---------------------- STOPS

function displayGTFSStops() {
	var sql = encodeURIComponent(stopsGTFS);
	var query = new google.visualization.Query(
			'http://www.google.com/fusiontables/gvizdata?tq=' + sql);
	query.send(function(response) {
		var rows = response.getDataTable();
		for ( var i = 0; i < rows.getNumberOfRows(); i++) {
			var model = { 'id' : rows.getValue(i, 0),
				'name' : rows.getValue(i, 1), 'desc' : rows.getValue(i, 2),
				'lat' : rows.getValue(i, 3), 'long' : rows.getValue(i, 4) };
			createStopMarker(model);
		}
	});
}

function createStopMarker(model) {
	var point = new google.maps.LatLng(model['lat'], model['long']);
	var id = model['id'];
	var name = model['name'];
	var myMarkerOpts = { position : point, map : map };
	var marker = new google.maps.Marker(myMarkerOpts);
	var infoWindow = new google.maps.InfoWindow();

	google.maps.event.addListener(marker, 'click', function() {
		if (openedInfoWindow != null) {
			openedInfoWindow.close();
		} else {
			openedInfoWindow = new google.maps.InfoWindow()
		}
		openedInfoWindow.setContent("<b>" + id + "</b> : " + name);
		openedInfoWindow.open(map, marker);
	});
}

